package com.ruoyi.web.controller.company.study;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.apache.catalina.filters.SessionInitializerFilter;
import org.apache.catalina.manager.util.SessionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.tomcat.jni.FileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.company.study.domain.StudyTrain;
import com.ruoyi.company.study.service.IStudyTrainService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 学习培训Controller
 * 
 * @author tzn
 * @date 2020-12-18
 */
@Controller
@RequestMapping("/company/train")
public class StudyTrainController extends BaseController
{
    protected final Logger logger = LoggerFactory.getLogger(StudyTrainController.class);

    private String prefix = "company/train";

    @Autowired
    private IStudyTrainService studyTrainService;

    @RequiresPermissions("company:train:view")
    @GetMapping()
    public String study()
    {
        return prefix + "/train";
    }

    /**
     * 查询学习培训列表
     */
    @RequiresPermissions("company:train:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StudyTrain studyTrain)
    {
        startPage();
        List<StudyTrain> list = studyTrainService.selectStudyTrainList(studyTrain);
        return getDataTable(list);
    }

    /**
     * 导出学习培训列表
     */
    @RequiresPermissions("company:train:export")
    @Log(title = "学习培训", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(StudyTrain studyTrain)
    {
        List<StudyTrain> list = studyTrainService.selectStudyTrainList(studyTrain);
        ExcelUtil<StudyTrain> util = new ExcelUtil<StudyTrain>(StudyTrain.class);
        return util.exportExcel(list, "study");
    }

    /**
     * 新增学习培训
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存学习培训
     */
    @RequiresPermissions("company:train:add")
    @Log(title = "学习培训", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file, @RequestParam(value="status",required=false) String status, @RequestParam(value="invalidTime",required=false) String invalidTime) throws IOException {
        StudyTrain studyTrain = new StudyTrain();
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        studyTrain.setFilePath(fileName);
        studyTrain.setStatus(status);
        studyTrain.setInvalidTime(DateUtils.parseDate(invalidTime));
        studyTrain.setCreateUser(ShiroUtils.getLoginName());
        studyTrain.setFileName(StringUtils.substringBefore(file.getOriginalFilename(),"."));
        studyTrain.setFileType(StringUtils.substringAfter(file.getOriginalFilename(),"."));
        return toAjax(studyTrainService.insertStudyTrain(studyTrain));

    }

    /**
     * 修改学习培训
     */
    @GetMapping("/edit/{studyId}")
    public String edit(@PathVariable("studyId") Long studyId, ModelMap mmap)
    {
        StudyTrain studyTrain = studyTrainService.selectStudyTrainById(studyId);
        mmap.put("studyTrain", studyTrain);
        return prefix + "/edit";
    }

    /**
     * 修改保存学习培训
     */
    @RequiresPermissions("company:train:edit")
    @Log(title = "学习培训", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StudyTrain studyTrain)
    {
        return toAjax(studyTrainService.updateStudyTrain(studyTrain));
    }

    /**
     * 删除学习培训
     */
    @RequiresPermissions("company:train:remove")
    @Log(title = "学习培训", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        List<StudyTrain> list = studyTrainService.selectStudyTrainByIds(ids);
        for(int i = 0; i<list.size(); i++){
            String newfilePath = list.get(i).getFilePath().replace("/profile/upload",filePath);
            File file = new File(newfilePath);
            boolean isOk = file.exists();
            if(isOk){
                file.delete();
                logger.info(list.get(i).getStudyId()+"+删除成功！");
            }else{
                logger.info(list.get(i).getStudyId()+"+文件不存在！");
            }
        }
        return toAjax(studyTrainService.deleteStudyTrainByIds(ids));
    }
}
